import { NextRequest, NextResponse } from 'next/server'
import bcrypt from 'bcryptjs'
import prisma from '@/lib/prisma'

export async function POST(req: NextRequest) {
  try {
    const { name, email, password, role } = await req.json()

    // 验证输入
    if (!name || !email || !password || !role) {
      return NextResponse.json(
        { message: '请填写所有必填字段' },
        { status: 400 }
      )
    }

    // 验证角色是否有效
    if (!['STUDENT', 'TEACHER', 'ADMIN'].includes(role)) {
      return NextResponse.json(
        { message: '无效的角色类型' },
        { status: 400 }
      )
    }

    // 检查邮箱是否已注册
    const existingUser = await prisma.user.findUnique({
      where: { email },
    })

    if (existingUser) {
      return NextResponse.json(
        { message: '该邮箱已被注册' },
        { status: 400 }
      )
    }

    // 密码加密
    const hashedPassword = await bcrypt.hash(password, 10)

    // 创建用户
    const user = await prisma.user.create({
      data: {
        name,
        email,
        password: hashedPassword,
        role,
      },
    })

    // 返回用户信息（排除密码）
    const { password: _, ...userWithoutPassword } = user

    return NextResponse.json(
      {
        message: '注册成功',
        user: userWithoutPassword,
      },
      { status: 201 }
    )
  } catch (error) {
    console.error('注册失败:', error)
    return NextResponse.json(
      { message: '服务器错误' },
      { status: 500 }
    )
  }
} 